package uns.fit.gis.ui;

import java.io.ByteArrayInputStream;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.TextField;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import uns.fit.gis.MapDrawer;
import uns.fit.gis.Util;
import uns.fit.gis.httpconnection.MHttpConnItem;
import uns.fit.gis.httpconnection.MHttpConnection;
import uns.fit.gis.httpconnection.MHttpConnectionHandler;
import uns.fit.gis.i18n.LocaleManager;
import uns.fit.gis.settings.MapSettings;
import uns.fit.gis.xml.BasicHandler;

public class SettingsForm extends Form implements CommandListener, MHttpConnectionHandler {
	private MapDrawer midlet;

	private TextField username, password;
	private TextField url;
	private TextField delay;
	private TextField id;
	private TextField storageFolder;
	private Command okCommand;
	private Command backCommand;
	private StringBuffer b = new StringBuffer();
	private String info;
	private String data;

    private SAXParserFactory factory;
	private SAXParser parser;
	
	private ChoiceGroup localeGroup;
	
	private ChoiceGroup streetNameGroup;
	
	public SettingsForm(String title, MapDrawer midlet) {
		super(title);
		this.midlet = midlet;

		okCommand = new Command(LocaleManager.getMessage("ok"), Command.OK, 1);
		addCommand(okCommand);
		backCommand = new Command(LocaleManager.getMessage("back"), Command.BACK, 2);
		addCommand(backCommand);
		/*
		username = new TextField("Username","",10,TextField.ANY);
		append(username);
		password = new TextField("Password","",10,TextField.PASSWORD);
		append(password);
		*/
		url = new TextField("URL", midlet.getSettings().getUrlUpdatePosition(), 300, TextField.ANY);
		append(url);
		delay = new TextField(LocaleManager.getMessage("delaytime"), String.valueOf(midlet.getSettings().getServerDelayTime()),10,TextField.NUMERIC);
		append(delay);
		id = new TextField("Id", String.valueOf(midlet.getSettings().getDeviceId()),10,TextField.NUMERIC);
		append(id);
		storageFolder = new TextField(LocaleManager.getMessage("storagefolder"), String.valueOf(midlet.getSettings().getStorageFolder()),100,TextField.ANY);
		append(storageFolder);
		
		addLocaleGroup();
		addStreetNameGroup();
		
		setCommandListener(this);
	}

	public SettingsForm(String title) {
		super(title);
		// TODO Auto-generated constructor stub
	}

	public SettingsForm(String arg0, Item[] arg1) {
		super(arg0, arg1);
		// TODO Auto-generated constructor stub
	}

	public void commandAction(Command command, Displayable displayable) {
		if (command == okCommand) {
			/*
			if (username.getString().equals("")) {

			} else {
				new Thread() {
					public void run() {
						login(username.getString(), password.getString());
					}
				}.start();
				
			}
			*/
			
			if(url.getString().length() > 0) {
				Util.UPDATE_POSITION_URL = url.getString();
				midlet.getSettings().setUrlUpdatePosition(Util.UPDATE_POSITION_URL);
			}
			if(delay.getString().length() > 0) {
				Util.SERVER_DELAY_TIME = Integer.valueOf(delay.getString()).intValue();
				midlet.getSettings().setServerDelayTime(Util.SERVER_DELAY_TIME);
			}
			if(id.getString().length() > 0) {
				Util.DEVICE_ID = Integer.valueOf(id.getString()).intValue();
				midlet.getSettings().setDeviceId(Util.DEVICE_ID);
			}
			if(storageFolder.getString().length() > 0) {
				Util.STORAGE_FOLDER = storageFolder.getString();
				midlet.getSettings().setStorageFolder(Util.STORAGE_FOLDER);
			}
			
			midlet.getSettings().setLocale(LocaleManager.getSupportedLocales()[localeGroup.getSelectedIndex()]);
			if(streetNameGroup.isSelected(0))
				midlet.getSettings().setStreetNameIsAlong(true);
			else
				midlet.getSettings().setStreetNameIsAlong(false);
			
			midlet.showMapCanvas();
		} else if (command == backCommand) {
			midlet.showMapCanvas();
		}
	}

	private void login(String username, String password) {
		
		String url = "http://localhost:1234/WebSite1/Service.asmx/HelloWorld";
		
		
                    String data = "username=" + username + "&password=" + password;
                    MHttpConnItem item = new MHttpConnItem(0, this, url, false, true, data.getBytes());
                    MHttpConnection conn = new MHttpConnection();
                    conn.addItem(item);
                    conn.start();

			
	}

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

    public int HttpLoadCompleted(byte[] data, int errorCode, MHttpConnItem item) {
        if (data == null)
            System.out.println("NULL");
        else {
            String strXML = new String(data);
            System.out.println(strXML);
            try {
                factory = SAXParserFactory.newInstance();
                parser = factory.newSAXParser();

                ByteArrayInputStream bais = new ByteArrayInputStream(data);
                parser.parse(bais, new BasicHandler());
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }
    
    private void addLocaleGroup() {
        MapSettings settings = midlet.getSettings();

        //TODO: translate
        String[] localeLabels = {LocaleManager.getMessage("vi"),
    			LocaleManager.getMessage("en")};

        localeGroup =
                new ChoiceGroup(LocaleManager.getMessage("language"),
                ChoiceGroup.EXCLUSIVE, localeLabels, null);

        String currentLocale = settings.getLocale();
        // select EN, in case locale was not found
        localeGroup.setSelectedIndex(0, true);
        //select current locale
        for(int i=0; i<LocaleManager.getSupportedLocales().length; i++)
        {
            if(currentLocale.equals(LocaleManager.getSupportedLocales()[i]))
            {
                localeGroup.setSelectedIndex(i, true);
                break;
            }
        }

        this.append(localeGroup);
    }
    
    private void addStreetNameGroup() {
    	String[] type = {LocaleManager.getMessage("alongpath"),
    			LocaleManager.getMessage("horizontal")};

        streetNameGroup =
                new ChoiceGroup(LocaleManager.getMessage("streetnamedirection"),
                ChoiceGroup.POPUP, type, null);
        
        if(midlet.getSettings().getStreetNameIsAlong())
        	streetNameGroup.setSelectedIndex(0, true);
        else
        	streetNameGroup.setSelectedIndex(1, true);
        
        append(streetNameGroup);
    }
}
